<template>

  <div class="app-container calendar-list-container">

    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户ID" v-model="listQuery.userId">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="名字" v-model="listQuery.userName">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="电话" v-model="listQuery.phone">
      </el-input>
      <el-select clearable  @change='handleFilter' class="filter-item" style="width: 130px" v-model="listQuery.isActivation" placeholder="状态">
        <el-option label="激活" value="1">
        </el-option>
        <el-option label="未激活" value="0">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <!--<el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">新增</el-button>-->
      <!--<el-button class="filter-item" type="primary" :loading="downloadLoading"  icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <el-table :data="list.slice((currentPage-1)*pageSize,currentPage*pageSize)"
              v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row >
      <el-table-column align="center" label='排序' width="80">
        <template slot-scope="scope">
          {{scope.$index}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='用户ID' width="100">
        <template slot-scope="scope">
          {{scope.row.userId}}
        </template>
      </el-table-column>
      <el-table-column label="名字" width="170" align="center">
        <template slot-scope="scope">
          {{scope.row.userName}}
        </template>
      </el-table-column>
      <el-table-column label="电话" width="120" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="性别" width="90" align="center">
        <template slot-scope="scope">
          {{scope.row.sex === 2 ? "男" : "女"}}
        </template>
      </el-table-column>-->

      <!--<el-table-column label="上级ID" width="100" align="center">
        <template slot-scope="scope">
          {{scope.row.pid}}
        </template>
      </el-table-column>-->

      <el-table-column label="等级" width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.levelName}}
        </template>
      </el-table-column>

      <el-table-column label="时间" width="165" align="center">
        <template slot-scope="scope">
          {{scope.row.loginTime}}
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isActivation | statusFilter">{{scope.row.isActivation === 0 ? '未激活' : '激活'}}</el-tag>
        </template>
      </el-table-column>
      <!--<el-admin-column align="center" prop="created_at" label="Display_time" width="200">-->
      <!--<template slot-scope="scope">-->
      <!--<i class="el-icon-time"></i>-->
      <!--<span>{{scope.row.display_time}}</span>-->
      <!--</template>-->
      <!--</el-admin-column>-->
      <el-table-column  label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)" size="mini">修改</el-button>
          <el-button  size="mini" type="success" @click="showDTable(scope.row)" >账户</el-button>
          <!--<el-button size="mini" type="danger" >删除</el-button>-->
          <!--<el-button  size="mini" type="warning" @click="mShowUserVouchers(scope.row)" >优惠福利</el-button>-->
          <el-button type="danger" size="mini" @click="handleVoucherCreate(scope.row)">福利券</el-button>
          <el-button type="warning" size="mini" @click="handleWinnerCreate(scope.row)">加入中奖</el-button>
          <!--<el-button type="success" size="mini" plain @click="getMySuperiorList(scope.row.userId)">上级</el-button>-->
          <!--<el-button type="primary" size="mini" plain @click="getMyChildrenList(scope.row.userId)">下级</el-button>-->
          <el-button type="success" size="mini" plain @click="getMySuperiorList1(scope.row)">上级</el-button>
          <el-button type="primary" size="mini" plain @click="getMyChildrenList1(scope.row)">下级</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding-top: 15px;text-align: center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page=currentPage
        :page-sizes="[10, 20, 30]"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="80px" style='width: 400px; margin-left:50px;'>

        <el-form-item label="名字" prop="userName">
          <el-input v-model="temp.userName"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone"></el-input>
        </el-form-item>

        <el-form-item label="上级ID" prop="pid">
          <el-input v-model="temp.pid"></el-input>
        </el-form-item>


        <!--<el-form-item label="性别" prop="sex">
          <el-select class="filter-item" prop="sex" v-model="temp.sex" placeholder="请选择">
            <el-option
              v-for="item in sexs"
              :key="item.name"
              :label="item.name"
              :value="item.name" >
            </el-option>
          </el-select>
        </el-form-item>-->

        <el-form-item label="等级" prop="levelId" >
          <el-select disabled class="filter-item" prop="levelId" v-model="temp.levelId" placeholder="请选择">
            <el-option
              v-for="item in levelList"
              :key="item.levelId"
              :label="item.name"
              :value="item.levelId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="isActivation">
          <el-select class="filter-item" prop="isActivation" v-model="temp.isActivation" placeholder="请选择">
            <el-option
              v-for="item in status"
              :key="item.val"
              :label="item.name"
              :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
        <el-button  :loading="buttonLoading" v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

    <!--<el-dialog title="账户信息" :visible.sync="dialogTableVisible">
      <el-table :model="list1" border >
        <el-table-column prop="points" label="积分" width="100">
          <template slot-scope="scope">
            {{scope.row.points}}
          </template>
        </el-table-column>
        <el-table-column prop="growth" label="成长值" width="110">
          <template slot-scope="scope">
            {{scope.row.growth}}
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="会员卡余额" width="120">
          <template slot-scope="scope">
            {{scope.row.balance}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" >
          <el-button type="success" size="mini" plain @click="">修 改</el-button>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisible = false">确 定</el-button>
      </div>
    </el-dialog>-->



    <el-dialog title="账户信息:" :visible.sync="dialogFormVisiblessss" width="560px">
      <el-form :model="accountTemp"  label-position="right"  style='width: 260px; margin-left:70px;'>

        <el-form-item label="积分:">
            <el-input v-model="accountTemp.points"  auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="成长值:">
            <el-input v-model="accountTemp.growth"  auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="会员卡余额:">
            <el-input v-model="accountTemp.balance" auto-complete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info"  plain @click="dialogFormVisiblessss = false">取 消</el-button>
        <el-button type="danger"  plain @click="MergeAccount" >修 改</el-button>
      </div>
    </el-dialog>

    <!--<el-dialog title="优惠福利" :visible.sync="dialogTableVisibles">
      <el-table :data="voucherList" border ref="voucherList">
        <el-table-column type="selection" align="center" width="80"></el-table-column>
        <el-table-column type="hidden" prop="voucherId" align="center" width="80"></el-table-column>
        <el-table-column align="center" prop="sellerName" width="210" label="商家名" ></el-table-column>
        <el-table-column align="center" prop="content" label="福利劵内容" ></el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisibles = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisibles = false">确 定</el-button>
      </div>
    </el-dialog>-->


    <el-dialog title="送福利券" :visible.sync="dialogFormVisibles">
      <el-form :model="voucherTemp" ref="dataForms" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="福利券内容:" width="100">
          <el-input v-model="voucherTemp.content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item  label="到期时间:" class="postInfo-container-item" prop="time">
          <el-date-picker
            v-model="voucherTemp.time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取 消</el-button>
        <el-button :loading="buttonLoading" v-if="dialogStatus=='create'" type="primary" @click="VoucherDate">确认</el-button>
      </div>
    </el-dialog>


    <el-dialog title="设置：加入中奖" :visible.sync="dialogFormVisibless">
      <el-form :model="winnerTemp"  label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="活动名称：" prop="activityName">
          <el-select class="filter-item"  v-model="winnerTemp.activityId" placeholder="请选择">
            <el-option
              v-for="item in activityName"
              :key="item.activityId"
              :label="item.name"
              :value="item.activityId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="中奖时间:" class="postInfo-container-item" prop="createTime" >
          <el-date-picker
            v-model="winnerTemp.time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="权  重:" width="100">
          <el-input v-model="winnerTemp.sort" auto-complete="off" placeholder="数字越大值越大"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibless = false">取 消</el-button>
        <el-button :loading="buttonLoading" v-if="dialogStatus=='create'" type="primary" @click="WinnerCreate">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog title="我的下级" :visible.sync="dialogTableVisibless">
      <el-table :data="myChildrenList"  style="width: 100%;" :row-class-name="tableRowClassName">
        <el-table-column prop="ID" label="用户ID" width="150">
          <template slot-scope="scope">
            {{scope.row.userId}}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" width="260">
          <template slot-scope="scope">
          {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="200">
          <template slot-scope="scope">
            {{scope.row.phone}}
          </template>
        </el-table-column>
        <el-table-column prop="levelName" label="等级" width="150">
          <template slot-scope="scope">
            {{scope.row.levelName}}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisibless = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisibless = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="我的上级" :visible.sync="dialogTableVisiblesss">
      <el-table :data="mySuperiorList"  style="width: 100%;" :row-class-name="tableRowClassName">
        <el-table-column prop="ID" label="用户ID" width="150">
          <template slot-scope="scope">
            {{scope.row.userId}}
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" width="260">
          <template slot-scope="scope">
            {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="200">
          <template slot-scope="scope">
            {{scope.row.phone}}
          </template>
        </el-table-column>
        <el-table-column prop="levelName" label="等级" width="150">
          <template slot-scope="scope">
            {{scope.row.levelName}}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisiblesss = false">取 消</el-button>
        <el-button type="primary" @click="dialogTableVisiblesss = false">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>

  .filter-container{
    padding-bottom: 20px;
  }

</style>

<script>
  import { List, Merge, MergeWinner, initLevel, getMyChildren, getMySuperior, MergeAccount } from '../../api/user'
  import { splice } from '../../utils/common'
  // import { List as voucherList } from '../../api/voucher'
  import { Account } from '../../api/user'
  import { Merge as batch } from '../../api/voucher'

  export default {

    data() {
      return {
        status: [
          { name: '未激活', val: 0 },
          { name: '激活', val: 1 }
        ],
        sexs: [
          { name: '男性', val: 1 },
          { name: '女性', val: 2 }
        ],
        activityName: [
          { name: '每日活动', activityId: 1 },
          { name: '每周活动', activityId: 2 },
          { name: '月度活动', activityId: 3 },
          { name: '年度活动', activityId: 4 }
        ],
        list: [],
        list1: {},
        voucherList: null,
        levelList: null,
        userByVoucherList: null,
        listLoading: true,
        buttonLoading: false,
        listQuery: {
          userName: null,
          phone: null,
          isActivation: null
        },
        temp: {
          userId: null,
          userName: '',
          phone: '',
          sex: '',
          isActivation: '',
          pid: '',
          levelId: ''
        },
        accountTemp: {
          accountId: '',
          points: '',
          growth: '',
          balance: '',
          userId: '',
          createTime: ''
        },
        voucherTemp: {
          userId: '',
          content: '',
          time: ''
        },
        winnerTemp: {
          userId: '',
          activityId: '',
          time: '',
          sort: ''
        },
        dialogFormVisible: false,
        dialogFormVisibles: false,
        dialogFormVisibless: false,
        dialogFormVisiblesss: false,
        dialogFormVisiblessss: false,
        dialogTableVisible: false,
        dialogTableVisibles: false,
        dialogTableVisibless: false,
        dialogTableVisiblesss: false,
        dialogStatus: '',
        downloadLoading: false,
        textMap: {
          update: '编辑用户信息：',
          create: '新增用户信息：'
        },
        rules: {
          userName: [{ required: true }],
          phone: [{ required: true }],
          isActivation: [{ required: true }],
          pid: [{ required: true }],
          levelId: [{ required: true }],
          sex: [{ required: true }]
        },
        voucherRules: {
          voucherId: [{ required: true }],
          userId: [{ required: true }],
          content: [{ required: true }],
          time: [{ required: true }],
          isUse: [{ required: true }]
        },
        total: 0,
        currentPage: 1,
        pageSize: 10,
        activity: null,
        myChildrenList: null,
        mySuperiorList: null
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          // draft: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
    },
    mounted() {
    },
    methods: {
      // getMyChildrenList(userId) {
      //   this.dialogTableVisibless = true
      //   getMyChildren(userId).then(res => {
      //     this.myChildrenList = res.data
      //   }).catch(reason => {
      //     console.log(reason)
      //     this.buttonLoading = false
      //   })
      // },
      getMyChildrenList1(row) {
        getMyChildren(row.userId).then(response => {
          this.list = response.data
          this.total = response.data.length
          this.currentPage = 1
          console.log('下级' + this.list)
          // console.log(this.list)
          // this.myChildrenList.forEach((item) => {
          //   this.listQuery.userId = item.userId
          //   console.log(this.listQuery.userId)
          //   List(this.listQuery.userId, this.listQuery.userName, this.listQuery.phone, this.listQuery.isActivation).then(response => {
          //     this.list = response.data
          //   })
          // })
        }).catch(reason => {
          console.log(reason)
        })
      },
      // getMySuperiorList(userId) {
      //   this.dialogTableVisiblesss = true
      //   getMySuperior(userId).then(res => {
      //     this.mySuperiorList = res.data
      //   }).catch(reason => {
      //     console.log(reason)
      //     this.buttonLoading = false
      //   })
      // },
      getMySuperiorList1(row) {
        getMySuperior(row.userId).then(res => {
          this.list = res.data
          console.log('上级' + this.list)
          this.total = res.data.length
          this.currentPage = 1
          // this.list = this.mySuperiorList
          // this.listQuery.userId = this.mySuperiorList[0].userId
          // List(this.listQuery.userId, this.listQuery.userName, this.listQuery.phone, this.listQuery.isActivation).then(response => {
          //   this.list = response.data
          // })
        }).catch(reason => {
          console.log(reason)
        })
      },
      tableRowClassName({ row, rowIndex }) {
        if (rowIndex === 1) {
          return 'warning-row'
        } else if (rowIndex === 3) {
          return 'success-row'
        }
        return ''
      },
      fetchData() {
        this.listLoading = true
        List(this.listQuery.userId, this.listQuery.userName, this.listQuery.phone, this.listQuery.isActivation).then(response => {
          this.list = response.data
          this.total = response.data.length
          this.currentPage = 1
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
      },
      handleCurrentChange(val) {
        this.currentPage = val
      },
      WinnerCreate() {
        MergeWinner(this.winnerTemp).then(res => {
          this.winnerTemp = res.data
          this.dialogFormVisibless = false
          this.buttonLoading = false
          this.$notify({
            title: '成功',
            message: '加入中奖成功',
            type: 'success',
            duration: 2000
          })
        }).catch(reason => {
          console.log(reason)
          this.buttonLoading = false
        })
      },
      MergeAccount() {
        MergeAccount(this.accountTemp).then(res => {
          console.log(res.data)
          this.dialogFormVisiblessss = false
          this.$notify({
            title: '成功',
            message: '会员卡余额修改成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }).catch(reason => {
          console.log(reason)
        })
      },
      // userByVoucher(row) {
      //   this.userByVoucherList = null
      //   this.$refs.voucherList.clearSelection()
      //   Account(row.userId).then(res => {
      //     this.userByVoucherList = res.data
      //     if (this.voucherList) {
      //       this.voucherList.forEach((item) => {
      //         if (row.userId === item.userId) {
      //           this.$refs.voucherList.toggleRowSelection(item)
      //         }
      //         this.VoucherDate()
      //       })
      //     }
      //     this.dialogTableVisibles = true
      //   }).catch(error => {
      //     this.dialogTableVisibles = false
      //     console.log(error)
      //   })
      // },
      // initVouchers() {
      //   if (this.voucherList == null) {
      //     voucherList(0, 1).then(res => {
      //       this.voucherList = res.data.list
      //     })
      //   }
      // },
      // mShowUserVouchers(row) {
      //   this.dialogTableVisibles = true
      //   this.userByVoucher(row)
      // },
      initLevels() {
        if (this.levelList == null) {
          initLevel(0, 1).then(res => {
            this.levelList = res.data
          })
        }
      },
      handleFilter() {
        this.fetchData()
      },
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleVoucherCreate(row) {
        this.voucherTemp = {}
        this.voucherTemp.userId = row.userId
        this.dialogStatus = 'create'
        this.dialogFormVisibles = true
      },
      handleWinnerCreate(row) {
        this.winnerTemp = {}
        this.winnerTemp.userId = row.userId
        this.dialogStatus = 'create'
        this.dialogFormVisibless = true
      },
      handleUpdate(row) {
        this.resetTemp()
        this.temp = splice(this.temp, row)
        this.initLevels()
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      handleDownload() {

      },
      createData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            Merge(this.temp).then(res => {
              this.temp = res.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          } else {
            console.log('验证失败')
          }
        })
      },
      updateData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            Merge(this.temp).then(res => {
              this.temp = res.data
              for (const v of this.list) {
                if (this.temp.userId === v.userId) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          }
        })
      },
      VoucherDate() {
        this.buttonLoading = true
        batch(this.voucherTemp).then(res => {
          this.voucherTemp = res.data
          this.dialogFormVisibles = false
          this.buttonLoading = false
          this.$notify({
            title: '成功',
            message: '送福利券成功',
            type: 'success',
            duration: 2000
          })
        }).catch(reason => {
          console.log(reason)
          this.buttonLoading = false
        })
      },
      showDTable(row) {
        Account(row.userId).then(res => {
          this.accountTemp = res.data
          this.accountTemp.points = (this.accountTemp.points || 0) + ''
          this.accountTemp.growth = (this.accountTemp.growth || 0) + ''
          this.accountTemp.balance = (this.accountTemp.balance || 0) + ''
          this.dialogFormVisiblessss = true
        }).catch(error => {
          this.dialogFormVisiblessss = false
          console.log(error)
        })
      },
      resetTemp() {
        this.temp = {
          userId: null,
          userName: '',
          phone: '',
          sex: '',
          isActivation: '',
          pid: '',
          levelId: ''
        }
      }
    }
  }
</script>
